const config = {
  token: "your 语雀 token",
  reposUrl: "https://www.yuque.com/yashujs/cf3hd2",
};

let arr = config["reposUrl"].split("/");
let data = [arr[arr.length - 2], arr[arr.length - 1]].join("/");

const url = "https://www.yuque.com/api/v2/repos/" + data + "/docs/";

function getTitle(activeFile) {
  return activeFile.path.replace(/\//g, "-").replace(/\.md$/, "");
}
function getSlug(activeFile) {
  let title = getTitle(activeFile);
  return toCode(title);
}
function getBody(activeFile) {
  return activeFile.unsafeCachedData;
}
function toCode(str) {
  //加密字符串
  //定义密钥，36个字母和数字
  var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var len = key.length; //获取密钥的长度
  var a = key.split(""); //把密钥字符串转换为字符数组
  var s = "",
    b,
    b1,
    b2,
    b3; //定义临时变量
  for (var i = 0; i < str.length; i++) {
    //遍历字符串
    b = str.charCodeAt(i); //逐个提取每个字符，并获取Unicode编码值
    b1 = b % len; //求Unicode编码值得余数
    b = (b - b1) / len; //求最大倍数
    b2 = b % len; //求最大倍数的于是
    b = (b - b2) / len; //求最大倍数
    b3 = b % len; //求最大倍数的余数
    s += a[b3] + a[b2] + a[b1]; //根据余数值映射到密钥中对应下标位置的字符
  }
  return s; //返回这些映射的字符
}

async function uploadData(data) {
  let result = await request({
    url: url,
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Auth-Token": config.token,
    },
    body: JSON.stringify(data),
  });
  console.log("result =");
  console.log(JSON.parse(result));
}
module.exports = async (params) => {
  const activeFile = params.app.workspace.getActiveFile();
  if (!activeFile) {
    new Notice("No active file.");
    return;
  }
  let title = getTitle(activeFile);
  let slug = getSlug(activeFile);
  let body = getBody(activeFile);
  let data = {
    title,
    slug,
    body,
  };
  await uploadData(data);
  new Notice("Finished!");
};
